import 'dart:io';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;

import '../../../models/banner.dart';
import '../../../services/auth_service.dart';
import '../../../services/banner_service.dart';

class AddBannerLogic extends GetxController {
  final AuthService _authService = AuthService();
  final BannerService _bannerService = BannerService();
  final ImagePicker _imagePicker = ImagePicker();

  final descriptionController = TextEditingController();
  final websiteUrlController = TextEditingController();

  final isLoading = false.obs;
  final Rx<File?> selectedImage = Rx<File?>(null);

  @override
  void onClose() {
    descriptionController.dispose();
    websiteUrlController.dispose();
    super.onClose();
  }

  Future<void> pickImage(ImageSource source) async {
    try {
      final XFile? pickedFile = await _imagePicker.pickImage(
        source: source,
        imageQuality: 80, // Compress image quality to reduce file size
      );

      if (pickedFile != null) {
        selectedImage.value = File(pickedFile.path);
      }
    } catch (e) {
      SmartDialog.showToast('选择图片失败: $e');
    }
  }

  Future<String?> _saveImageToAppDirectory(File image) async {
    try {
      final appDir = await getApplicationDocumentsDirectory();
      final fileName = 'banner_${DateTime.now().millisecondsSinceEpoch}.jpg';
      final savedImage = await image.copy('${appDir.path}/$fileName');
      return savedImage.path;
    } catch (e) {
      print('Error saving image: $e');
      return null;
    }
  }

  Future<void> saveBanner() async {
    if (selectedImage.value == null) {
      SmartDialog.showToast('请选择一张图片');
      return;
    }

    if (descriptionController.text.trim().isEmpty) {
      SmartDialog.showToast('请输入描述');
      return;
    }

    if (websiteUrlController.text.trim().isEmpty) {
      SmartDialog.showToast('请输入网站链接');
      return;
    }

    // Validate URL format
    if (!_isValidUrl(websiteUrlController.text.trim())) {
      SmartDialog.showToast('请输入有效的网站链接，例如: https://example.com');
      return;
    }

    isLoading.value = true;

    try {
      final userId = await _authService.getCurrentUserId();
      if (userId == null) {
        SmartDialog.showToast('用户未登录');
        return;
      }

      // Save image to app directory
      String? imagePath;
      if (selectedImage.value != null) {
        imagePath = await _saveImageToAppDirectory(selectedImage.value!);
        if (imagePath == null) {
          SmartDialog.showToast('保存图片失败');
          return;
        }
      }

      final banner = BannerItem(
        imageUrl: imagePath!,
        description: descriptionController.text.trim(),
        websiteUrl: websiteUrlController.text.trim(),
        publisherId: userId,
      );

      await _bannerService.insertBanner(banner);
      SmartDialog.showToast('轮播图添加成功');
      Get.back();
    } catch (e) {
      SmartDialog.showToast('添加失败: $e');
    } finally {
      isLoading.value = false;
    }
  }

  bool _isValidUrl(String url) {
    // Simple URL validation
    if (!url.startsWith('http://') && !url.startsWith('https://')) {
      return false;
    }
    
    try {
      Uri.parse(url);
      return true;
    } catch (e) {
      return false;
    }
  }
}
